#!/usr/bin/nawk
#This is the nawk script developed by the California Air Resources Board, AQSB, OSS to take
#u v w ultrasonic data input columns 1, 2, 3 (u v w) and transpose it into degrees from north.,
# wind speed, and elevation. Written under the GNU Free Public License Agreement
# @http://www.gnu.org/licenses/gpl-3.0.txt. The algorithm for determining wind direction
# was contributed by Prof. Mark Princevak of University of California, Riverside,
# Department of Mechanical Engineering
# 
# The Vertical Algorithm was adapted to CARB standards and written
# by Joe Rohr.
# DEFINITION(S): 
# 1) atan2 (y,x) returns arctan (y/x) in radians
# 2) abs returns the absoulte value
BEGIN{ PI=3.1415926535 }\
function abs(x) {return sqrt(x*x)}
function deg2rad(degrees) { return (degrees/180)*3.141592635}\
function rad2deg(radians) { return (radians/3.141592635)*180}\
function Azim(u,v) { if (u==0 && v==0) return 0;
#Modified the (u==0 && v>0) case to return 0 instead of 180	 	
		else if (u==0 && v>0) return 0;
#Modified the (u==0 && v<0) case to return 180 instead of 0
		else if (u==0 && v<0) return 180;
#Modified the (u<0 && v==0) case to return 270 instead of 90 
		else if (u<0 && v==0 ) return 270;
#Modified the (u>0 && v==0) case to return 90 instead of 270
		else if (u>0 && v==0) return 90;
#Modified v>0 and u>0 case to not add 180, and invert v and u
		else if (v>0 && u>0) return atan2(u,v)*180/PI;
#Modified v<0 and u>0 case to not subtract from 360, instead to add 90
		else if (v<0 && u>0) return 90+atan2(abs(v),u)*180/PI;
#Modified v<0 and u<0 case to not subtract from 90, instead to add 180
		else if (v<0 && u<0) return 180+atan2(abs(u),abs(v))*180/PI;
#Modified v>0 and u<0 case to not subtract from 180, instead to add 270
		else if (v>0 && u<0) return 270+atan2(v,abs(u))*180/PI;
		else return "ERROR"}\
# 5B8967 [ UVW Ts AZIMUTH ELEVATION 2D-SPEED 3D-SPEED ]

END { 
	printf("%.2f,",Azim($1,$2));
}
    